package com.example.basic.config;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.basic.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * ClassName: JwtInterceptor
 * Description:
 * date: 2021/12/14 11:51
 * author zesion lee
 */
@Component
@Order(1)
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        if (token == null) {
            handle(request, response, "未设置token");
            return false;
        }
        try {
            Integer userId = Integer.valueOf(JwtUtil.getUserId(token));
            RequestHolder.addUserId(userId);
        } catch (TokenExpiredException exception) {
            handle(request, response, "token已过期");
            return false;
        } catch (JWTDecodeException exception) {
            handle(request, response, "token错误");
            return false;
        }

        return true;
    }

    private void handle(HttpServletRequest request, HttpServletResponse response, String msg) {
        response.setStatus(403);
        try {
            PrintWriter writer = response.getWriter();
            writer.println(msg);
            log.info("请求 Method:{} Url:{}, Result:{}", request.getMethod(), request.getRequestURI(), msg);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
